from django.db import models
from django.contrib.auth import get_user_model
from django.conf import settings
import uuid

User = get_user_model()


class BaseModel(models.Model):
    """基础模型类"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    
    class Meta:
        abstract = True


class AuditLog(models.Model):
    """审计日志模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='用户')
    action = models.CharField(max_length=100, verbose_name='操作')
    resource_type = models.CharField(max_length=50, verbose_name='资源类型')
    resource_id = models.CharField(max_length=100, null=True, blank=True, verbose_name='资源ID')
    result = models.CharField(max_length=20, choices=[
        ('success', '成功'),
        ('error', '失败'),
        ('warning', '警告')
    ], verbose_name='结果')
    details = models.JSONField(default=dict, verbose_name='详细信息')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    user_agent = models.TextField(null=True, blank=True, verbose_name='用户代理')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'common_audit_log'
        verbose_name = '审计日志'
        verbose_name_plural = '审计日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'created_at']),
            models.Index(fields=['action', 'created_at']),
            models.Index(fields=['resource_type', 'resource_id']),
        ]
    
    def __str__(self):
        return f"{self.user} - {self.action} - {self.result}"


class SystemConfig(models.Model):
    """系统配置模型"""
    key = models.CharField(max_length=100, unique=True, verbose_name='配置键')
    value = models.TextField(verbose_name='配置值')
    description = models.TextField(null=True, blank=True, verbose_name='描述')
    is_encrypted = models.BooleanField(default=False, verbose_name='是否加密')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'common_system_config'
        verbose_name = '系统配置'
        verbose_name_plural = '系统配置'
    
    def __str__(self):
        return f"{self.key}: {self.value[:50]}..."
    
    def get_value(self):
        """获取配置值（自动解密）"""
        if self.is_encrypted:
            from .security import encryption_manager
            try:
                return encryption_manager.decrypt(self.value)
            except Exception:
                return self.value
        return self.value
    
    def set_value(self, value, encrypt=False):
        """设置配置值（可选加密）"""
        if encrypt:
            from .security import encryption_manager
            self.value = encryption_manager.encrypt(value)
            self.is_encrypted = True
        else:
            self.value = value
            self.is_encrypted = False


class PerformanceMetric(models.Model):
    """性能指标模型"""
    metric_name = models.CharField(max_length=100, verbose_name='指标名称')
    metric_value = models.FloatField(verbose_name='指标值')
    metric_unit = models.CharField(max_length=20, null=True, blank=True, verbose_name='单位')
    tags = models.JSONField(default=dict, verbose_name='标签')
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='时间戳')
    
    class Meta:
        db_table = 'common_performance_metric'
        verbose_name = '性能指标'
        verbose_name_plural = '性能指标'
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['metric_name', 'timestamp']),
            models.Index(fields=['timestamp']),
        ]
    
    def __str__(self):
        return f"{self.metric_name}: {self.metric_value} {self.metric_unit or ''}"


class ErrorLog(models.Model):
    """错误日志模型"""
    error_type = models.CharField(max_length=100, verbose_name='错误类型')
    error_message = models.TextField(verbose_name='错误消息')
    stack_trace = models.TextField(null=True, blank=True, verbose_name='堆栈跟踪')
    request_path = models.CharField(max_length=500, null=True, blank=True, verbose_name='请求路径')
    request_method = models.CharField(max_length=10, null=True, blank=True, verbose_name='请求方法')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='用户')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    user_agent = models.TextField(null=True, blank=True, verbose_name='用户代理')
    extra_data = models.JSONField(default=dict, verbose_name='额外数据')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    resolved = models.BooleanField(default=False, verbose_name='已解决')
    
    class Meta:
        db_table = 'common_error_log'
        verbose_name = '错误日志'
        verbose_name_plural = '错误日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['error_type', 'created_at']),
            models.Index(fields=['resolved', 'created_at']),
        ]
    
    def __str__(self):
        return f"{self.error_type}: {self.error_message[:100]}..."


class CacheStats(models.Model):
    """缓存统计模型"""
    cache_key = models.CharField(max_length=255, verbose_name='缓存键')
    hit_count = models.IntegerField(default=0, verbose_name='命中次数')
    miss_count = models.IntegerField(default=0, verbose_name='未命中次数')
    last_accessed = models.DateTimeField(auto_now=True, verbose_name='最后访问时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'common_cache_stats'
        verbose_name = '缓存统计'
        verbose_name_plural = '缓存统计'
        unique_together = ['cache_key']
    
    @property
    def hit_rate(self):
        """命中率"""
        total = self.hit_count + self.miss_count
        return (self.hit_count / total * 100) if total > 0 else 0
    
    def __str__(self):
        return f"{self.cache_key}: {self.hit_rate:.1f}%"
